<!DOCTYPE html>
<html>
<head>
    <title>掘力值变化曲线</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <!--    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>-->
    <script src="{{ url_for('static', filename='chart.js') }}"></script>
    <!--    <script src="https://cdn.bootcdn.net/ajax/libs/Chart.js/4.5.0/chart.min.js"></script>-->
</head>
<body>
<div class="container">
    <h1>学习力看板</h1>
    <p id="top10Date"></p>
    <div class="overview">
        <h2>班级概况</h2>
        <div class="overview-grid">
            <div class="overview-item">
                <h3>总人数</h3>
                <p id="totalUsers">计算中...</p>
            </div>
            <div class="overview-item">
                <h3>平均分</h3>
                <p id="avgScore">计算中...</p>
            </div>
            <div class="overview-item">
                <h3>前三名</h3>
                <div id="top3List">计算中...</div>
            </div>
            <div class="overview-item">
                <h3>进步人数</h3>
                <p id="improvedCount">计算中...</p>
            </div>
            <div class="overview-item">
                <h3>进步最多</h3>
                <div id="top3Improvements">计算中...</div>
            </div>
        </div>
    </div>



<div class="leaderboard">
    <h2>掘力值排行榜 (Top 10)</h2>

    <table id="top10Table">
        <thead>
        <tr>
            <th>排名</th>
            <th>用户名</th>
            <th>掘力值</th>
            <th>地址</th>
        </tr>
        </thead>
        <tbody>
        <!-- 数据将通过 JavaScript 动态填充 -->
        </tbody>
    </table>
</div>
<div class="leaderboard">
    <h2>掘力值排行榜 (后10名)</h2>
    <p id="bottom10Date"></p>
    <table id="bottom10Table">
        <thead>
        <tr>
            <th>排名</th>
            <th>用户名</th>
            <th>掘力值</th>
            <th>地址</th>
        </tr>
        </thead>
        <tbody>
        <!-- 数据将通过 JavaScript 动态填充 -->
        </tbody>
    </table>
</div>
<div class="leaderboard">
    <h2>持续进步学生 (每次增长>10分)</h2>
    <p id="improvedDate"></p>
    <table id="improvedTable">
        <thead>
        <tr>
            <th>用户名</th>
            <th>最新掘力值</th>
            <th>增长次数</th>
            <th>地址</th>
        </tr>
        </thead>
        <tbody>
        <!-- 数据将通过 JavaScript 动态填充 -->
        </tbody>
    </table>
</div>
<div class="user-select">
    <select id="userSelect">
        {% for user in users %}
        <option value="{{ user['用户ID'] }}">{{ user['掘金用户名'] }}</option>
        {% endfor %}
    </select>
</div>
<div class="chart-container">
    <canvas id="powerChart"></canvas>
</div>
</div>
</div>
<script>
    const ctx = document.getElementById('powerChart').getContext('2d');
    const chart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: [],
            datasets: [{
                label: '掘力值',
                data: [],
                borderColor: 'rgb(75, 192, 192)',
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });

    async function updateChart(userId) {
    const response = await fetch(`/user/${userId}`);
    const data = await response.json();
    chart.data.labels = data.dates;
    chart.data.datasets[0].data = data.values;
    chart.data.datasets[0].label = `${data.username} 的掘力值`;
    chart.update();

}

document.getElementById('userSelect').addEventListener('change', (e) => {
    updateChart(e.target.value);
});


    async function updateTop10() {
const response = await fetch('/top10');
const data = await response.json();
const tableBody = document.querySelector('#top10Table tbody');
tableBody.innerHTML = ''; // 清空现有数据
data.forEach((user, index) => {
    const row = tableBody.insertRow();
    row.insertCell(0).textContent = index + 1;
    row.insertCell(1).textContent = user['掘金用户名'];
    const scoreCell = row.insertCell(2);
    scoreCell.textContent = '0'; // 初始显示0

    // 添加动画效果
    const targetValue = user['掘力值'];
    let currentValue = 0;
    const increment = targetValue / 50; // 将动画分成50帧
    const duration = 2000; // 动画持续2秒
    const stepTime = duration / 50; // 每帧的时间间隔
    const delay = index * 100; // 每行延迟100ms开始动画

    setTimeout(() => {
        const timer = setInterval(() => {
            currentValue += increment;
            if (currentValue >= targetValue) {
                currentValue = targetValue;
                clearInterval(timer);
            }
            scoreCell.textContent = Math.round(currentValue);
        }, stepTime);
    }, delay);

    const newCell = row.insertCell(-1);
    newCell.innerHTML = `<a href='https://juejin.cn/user/${user['用户ID']}' target='_blank'>去看看</a>`;
});

// 设置日期
const today = new Date().toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' });
document.getElementById('top10Date').textContent = `数据更新于: ${today}`;
}





    // 初始化排行榜
    updateTop10();

    async function updateBottom10() {
const response = await fetch('/bottom10');
const data = await response.json();
const tableBody = document.querySelector('#bottom10Table tbody');
tableBody.innerHTML = ''; // 清空现有数据
data.forEach((user, index) => {
    const row = tableBody.insertRow();
    row.insertCell(0).textContent = index + 1;
    row.insertCell(1).textContent = user['掘金用户名'];
    row.insertCell(2).textContent = user['掘力值'];
    const newCell = row.insertCell(-1);
    newCell.innerHTML = `<a href='https://juejin.cn/user/${user['用户ID']}' target='_blank'>去看看</a>`;
});

// 设置日期
const today = new Date().toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' });
document.getElementById('bottom10Date').textContent = `数据更新于: ${today}`;
}

// 在初始化部分添加调用
updateBottom10();



    async function updateImproved() {
const response = await fetch('/improved');
const data = await response.json();
const tableBody = document.querySelector('#improvedTable tbody');
tableBody.innerHTML = ''; // 清空现有数据

if (data.length === 0) {
    const row = tableBody.insertRow();
    row.insertCell(0).colSpan = 4;
    row.cells[0].textContent = '暂无持续进步的学生';
    row.cells[0].style.textAlign = 'center';
} else {
    data.forEach(user => {
        const row = tableBody.insertRow();
        row.insertCell(0).textContent = user['掘金用户名'];
        row.insertCell(1).textContent = user['最新掘力值'];
        row.insertCell(2).textContent = user['增长次数'];
        const newCell = row.insertCell(-1);
        newCell.innerHTML = `<a href='https://juejin.cn/user/${user['用户ID']}' target='_blank'>去看看</a>`;
    });
}

// 设置日期
const today = new Date().toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' });
document.getElementById('improvedDate').textContent = `数据更新于: ${today}`;
}

// 在初始化部分添加调用
updateImproved();
async function updateOverview() {
const response = await fetch('/overview');
const data = await response.json();

// 更新总人数
const totalUsersEl = document.getElementById('totalUsers');
animateValue(totalUsersEl, 0, data.total_users, 1000);

// 更新平均分
const avgScoreEl = document.getElementById('avgScore');
animateValue(avgScoreEl, 0, data.average_score, 1000, true);

// 更新前三名
const top3ListEl = document.getElementById('top3List');
top3ListEl.innerHTML = data.top3.map((user, index) =>
    `<p>${index + 1}. ${user['掘金用户名']} - ${user['掘力值']}分</p>`
).join('');

// 更新进步人数
const improvedCountEl = document.getElementById('improvedCount');
animateValue(improvedCountEl, 0, data.improved_count, 1000);

// 更新进步最多的前三名
const top3ImprovementsEl = document.getElementById('top3Improvements');
top3ImprovementsEl.innerHTML = data.top3_improvements.map((user, index) =>
    `<p>${index + 1}. ${user['掘金用户名']} (+${user['增长值']}分)</p>`
).join('');
}


function animateValue(element, start, end, duration, isFloat = false) {
const range = end - start;
const increment = range / (duration / 16);
let current = start;

const timer = setInterval(() => {
    current += increment;
    if ((increment > 0 && current >= end) || (increment < 0 && current <= end)) {
        current = end;
        clearInterval(timer);
    }
    element.textContent = isFloat ? current.toFixed(2) : Math.round(current);
}, 16);
}

// 在初始化部分添加调用
updateOverview();
setTimeout(()=>{
    const firstUser = document.querySelector('#userSelect option');
if (firstUser) {
    updateChart(firstUser.value);
}
},

2000);





</script>
</body>
</html>
